<script setup lang="ts" name="associated_shop_authorize">
import { getDict, getUserShopList, getPublicUserShopList } from '@/api'
import {
  MyResponse,
  PickerItem,
  DictData,
  AiAlarmInfo,
  ShopInfo,
  UserStaffType,
  UserShopListResponse
} from '@/api/types'
import { userUtil } from '@/utils/user-utils'
import 'vant/es/dialog/style'
import 'vant/es/image-preview/style'
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import noDataPng from '@/assets/no-data.png'
import { cacheUtil } from '@/utils/cache-utils'

const router = useRouter()
const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const totalSize = ref(0)
const list = ref<Array<ShopInfo>>([])

const shopId = ref('')
const showSearchPart = ref(true)

const loadingShopList = ref(false)

const alarmType = ref<PickerItem>({ label: '', value: '' })

const searchKeyword = ref('') // 新增搜索关键字
//修改staffType
const staffType = ref<string>('') // 只存储 valu
onMounted(() => {
  loadShopList()
})
function getRequestParams() {
  return {
    shopId: shopId.value,
    pageNumber: currentPage.value,
    pageSize: pageSize.value,
    isConfirm: changeTypeAuth.value.value as '0' | '1',
    ...(searchKeyword.value ? { keyword: searchKeyword.value } : {}),
    ...(staffType.value ? { staffType: staffType.value } : {})
  }
}

const onRefresh = async () => {
  shopId.value = userUtil.getUserShopId()
  currentPage.value = 1
  finished.value = false
  refreshing.value = true
  loading.value = true
  await onLoad()
}

const onLoad = async () => {
  let res: MyResponse<UserShopListResponse>
  const params = getRequestParams()
  if (changeType.value.value === '1') {
    res = await getUserShopList(params)
  } else {
    res = await getPublicUserShopList(params)
  }
  const newShopList = res?.data?.rows ?? []
  list.value = newShopList
  totalSize.value = Number(res?.data?.total ?? 0)
  loading.value = false
  finished.value = newShopList.length < pageSize.value
  currentPage.value += 1
}

const loadShopList = async () => {
  loadingShopList.value = true
  const params = getRequestParams()
  let res: MyResponse<UserShopListResponse>
  if (changeType.value.value === '1') {
    res = await getUserShopList(params)
  } else {
    res = await getPublicUserShopList(params)
  }
  const newShopList = res?.data?.rows ?? []
  if (refreshing.value) {
    list.value = []
    refreshing.value = false
  }
  list.value = newShopList
  loading.value = false
  finished.value = newShopList.length < pageSize.value
  currentPage.value += 1
  totalSize.value = newShopList.length
}
//整改状态
const changeType = ref<PickerItem>({ label: '公众', value: '0' })
const changeTypeOptions = ref<Array<PickerItem>>([
  { label: '公众', value: '0' },
  { label: '食品安全总监', value: '1' }
])

// 授权状态
const changeTypeAuth = ref<PickerItem>({ label: '待授权', value: '0' })
// 授权状态选项
const changeTypeAuthOptions = ref<Array<PickerItem>>([
  { label: '已授权', value: '1' },
  { label: '待授权', value: '0' }
])

//全部的加載接口
const loadAllType: Function = async function loadAlarmType(): Promise<
  Array<PickerItem>
> {
  const res: MyResponse<Array<DictData>> = await getDict('PUBLIC_TYPE')
  const list =
    res.data?.map((pickerItem): PickerItem => {
      return {
        label: pickerItem.name,
        value: pickerItem.code
      }
    }) ?? []
  // 在列表前面添加"全部"选项，value为空字符串
  return [{ label: '全部', value: '' }, ...list]
}
//添加按鈕的逻辑

//获取shop info对象

const shopInfo = ref<ShopInfo | null>(userUtil.getUserShop())
const shopTypeCode = computed(() => shopInfo.value?.shopTypeCode ?? '')

// 处理识别类型选择确认事件

// 监听 staffType 变化，但避免无限循环
watch(staffType, (newVal, oldVal) => {
  console.log('staffType changed from', oldVal, 'to', newVal)
  // 添加防抖或者条件判断避免频繁刷新
  if (newVal !== oldVal) {
    onRefresh()
  }
})
function jumpDetail(event: MouseEvent, item: AiAlarmInfo) {
  // 阻止事件冒泡
  event.stopPropagation()
  cacheUtil.clearAlarmInfo()
  router.push({
    path: '/correction_report',
    query: {
      shopId: userUtil.getUserShopId(),
      item: encodeURIComponent(JSON.stringify(item)),
      id: item.id,
      editable: item.auditStatus ? '' : 'true'
    }
  })
}
</script>
<template>
  <div>
    <div class="list-sel" style="margin-bottom: 0px">
      <div v-if="showSearchPart" class="pt-[10px]">
        <div class="tr items-center">
          <div class="name mr-[5px]"><span>*</span>整改状态</div>
          <div class="flex-auto">
            <form-select-picker
              v-model="changeType"
              :options="changeTypeOptions"
              placeholder="请选择整改状态"
            />
          </div>
        </div>
        <div class="tr items-center">
          <div class="name mr-[5px]"><span>*</span>授权状态</div>
          <div class="flex-auto">
            <form-select-picker
              v-model="changeTypeAuth"
              :options="changeTypeAuthOptions"
              placeholder="请选择授权状态"
            />
          </div>
        </div>
        <div class="tr items-center" v-if="changeType?.value === '0'">
          <div class="name mr-[5px]"><span>*</span>人员类型</div>
          <div class="flex-auto">
            <form-select-picker
              v-model="staffType"
              :loader="loadAllType"
              placeholder="请选择人员类型"
              clearable
            />
          </div>
        </div>

        <div v-if="showSearchPart" class="pt-[10px]">
          <div class="tr items-center">
            <div class="name mr-[5px]"><span>*</span>人员姓名</div>
            <div class="flex-auto">
              <van-field
                v-model="searchKeyword"
                class="van-field"
                clearable
                placeholder="请输入人员姓名/电话"
              />
            </div>
          </div>
          <div class="btn-box flex flex-col items-center">
            <a href="javascript:;" class="btn w-full" @click="onRefresh"
              >查询</a
            >
          </div>
        </div>

        <div ref="listBox" class="list-wrap4">
          <div class="title mt-[1.6rem]">
            <div class="name">查询结果</div>
            <div class="r">
              总数量<span>{{ totalSize }}</span
              >条
            </div>
          </div>
          <div class="list-box2">
            <van-empty
              v-if="!loading && finished && list.length <= 0"
              :image="noDataPng"
              image-size="160"
              description="暂无数据"
            />
            <van-list
              v-if="list.length > 0 || loading"
              ref="vantList"
              v-model:loading="loading"
              :finished="finished"
              finished-text="没有更多了"
              @load="onLoad"
            >
              <div
                v-for="item in list"
                :key="item.id"
                class="item"
                @click="jumpDetail($event, item)"
              >
                <div
                  :class="[
                    item.isConfirm === null || item.isConfirm === undefined
                      ? 'state state2'
                      : item.isConfirm === '1'
                        ? 'state'
                        : item.isConfirm === '0'
                          ? 'state state2'
                          : 'state state2'
                  ]"
                >
                  {{
                    item.isConfirm === null || item.isConfirm === undefined
                      ? '待完善'
                      : item.isConfirm === '1'
                        ? '已授权'
                        : item.isConfirm === '0'
                          ? '待授权'
                          : '未通过'
                  }}
                </div>
                <div class="ellipsis-title">
                  {{ (item.shopName ?? '') + `(${item.unitName})` }}
                </div>

                <div class="info-fields-container">
                  <div
                    class="b it mb-[8px]"
                    v-for="field in getDisplayFields(item)"
                    :key="field.label"
                  >
                    {{ field.label }} : {{ field.value ?? '' }}
                  </div>
                </div>

                <div class="flex flex-row w-full mt-[8px]">
                  <div
                    v-if="
                      shopTypeCode &&
                      shopTypeCode.startsWith('002') &&
                      changeType.value === '0'
                    "
                    class="text-[#2163e0] bg-[#f5f9ff] border-[#cedfff] border-solid border-2 rounded-[0.4rem] py-[0.4rem] mx-[0px] text-center flex-1 mr-[10px]"
                    @click="jumpDetail($event, item)"
                  >
                    修改
                  </div>

                  <div
                    v-if="changeTypeAuth.value === '0'"
                    class="text-[#2163e0] bg-[#f5f9ff] border-[#cedfff] border-solid border-2 rounded-[0.4rem] py-[0.4rem] mx-[0px] text-center flex-1 mr-[10px]"
                    @click="jumpDetail($event, item)"
                  >
                    授权
                  </div>
                  <div
                    class="text-[#fe3737] bg-[#ffebeb] border-[#ffc8c8] border-solid border-2 rounded-[0.4rem] py-[0.4rem] mx-[0px] text-center flex-1"
                    @click="logoff($event, item)"
                  >
                    删除
                  </div>
                </div>
              </div>
            </van-list>
          </div>
          <van-back-top />
        </div>
      </div>
      <van-floating-bubble
        v-if="
          changeTypeAuth.value === '0' &&
          shopTypeCode &&
          shopTypeCode.startsWith('002') &&
          changeType.value === '0'
        "
        icon="add"
        axis="lock"
        @click="addEmployess"
      />
    </div>
  </div>
</template>

<style scoped>
.icon-close {
  width: 15px;
  height: 15px;
  background-image: url('@/assets/icon-collapse.png');
  background-size: contain; /* 使背景图片适应元素尺寸，保持宽高比 */
  background-position: center; /* 确保背景图片居中显示 */
  background-repeat: no-repeat; /* 防止背景图片重复 */
}
.ellipsis-title {
  font-size: 1.3rem;
  overflow: hidden;
  text-overflow: ellipsis;
  box-sizing: border-box;
  padding-right: 2rem;
  display: block;
  margin-bottom: 0.8rem;
}
</style>
